'use strict'

require('./index.css');
require('page/common/nav-simple/index.js');
var _mm = require('util/mm.js');
var _user = require('service/user-service.js');

$(function () {
    page.init();
});

var page = {
    init: function () {
        this.bindEvent();
    },
    bindEvent: function () {
        var _this = this;
        //登录按钮点击事件
        $('.btn-submit').click(function () {
            _this.submit();
        });
        //回车键事件
        $('.user-content').keyup(function (e) {
            if (e.keyCode === 13) {
                _this.submit();
            }
        });
    },
    //提交
    submit: function () {
        console.log('submit');
        var _this = this;
        var formData = {
                username: $.trim($('#username').val()),
                password: $.trim($('#password').val())
            },
            validateResult = this.formValidate(formData);
        if (validateResult.status) {
            console.log('aaa');
            _user.login(formData, function (res) {
                console.log(res);
                console.log(_mm.getUrlParam('redirect') || './index.html');
                window.location.href = _mm.getUrlParam('redirect') || './index.html';

                //                _this.test();
            }, function (err) {
                console.log(err);
                formError.show(err);
            });
        }
        //验证不通过
        else {
            formError.show(validateResult.msg);
        }
    },
    test: function () {
        _user.checkLogin(function (res) {
            console.log('checklogin res===' + res);
        }, function (errMsg) {
            console.log('checklogin errMsg===' + errMsg);
        });
    },
    //用户名密码验证
    formValidate: function (formData) {
        var result = {
            status: false,
            msg: ''
        };
        if (!_mm.validate(formData.username, 'require')) {
            result.msg = '用户名不能为空';
            return result;
        };
        if (!_mm.validate(formData.password, 'require')) {
            result.msg = '密码不能为空';
            return result;
        };
        result.status = true;
        result.msg = '验证通过';
        return result;
    }
};

var formError = {
    show: function (msg) {
        $('.error-item').show().find('.err-msg').text(msg);
    },
    hide: function () {
        $('.error-item').hide().find('.err-msg').text('');
    }
};
